<template>
  <div class="app-container">
    <el-card v-loading="pageLoading" shadow="never">
      <PaginationTable :table-data="tableData" :columns="columns" :show-pagination="false">
        <!-- 自定义列内容 -->
        <template #subscribeStatus="scope">
          {{ subscribeStatusMap[scope.row.subscribeStatus] || "--" }}
        </template>
        <template #operate="scope">
          <el-button
            v-if="Number(scope.row.subscribeStatus) === 0"
            type="primary"
            link
            @click="subscribeEvent(scope.row, 1)"
          >
            订阅
          </el-button>
          <el-button
            v-if="Number(scope.row.subscribeStatus) === 1"
            type="primary"
            link
            @click="subscribeEvent(scope.row, 0)"
          >
            取消订阅
          </el-button>
        </template>
      </PaginationTable>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import PaginationTable, { TableColumn } from "@/views/templatePage/PaginationTable/index.vue";
import PermissionsManageAPI, { EventListInfo } from "@/api/permissionsManage";
import { getHasOperatePermission } from "@/utils/auth";
// 判断是否拥有权限
const hasOperatePermission: boolean = getHasOperatePermission();
// 表格数据
const tableData = ref<EventListInfo[]>([]);
// 列配置
const columns: TableColumn[] = [
  { prop: "desc", label: "消息事件", headerAlign: "left", align: "left", show: true },
  { prop: "className", label: "所属权限类目", show: true },
  { prop: "remark", label: "说明", show: true },
  { prop: "subscribeStatus", slot: "subscribeStatus", label: "订阅状态", show: true },
  { prop: "subscribedTime", label: "订阅时间", show: true },
  {
    prop: "operate",
    slot: "operate",
    label: "操作",
    headerAlign: "right",
    align: "right",
    show: hasOperatePermission,
  },
].filter((item) => item.show) as TableColumn[];
// 角色类型
const subscribeStatusMap: Record<number, string> = {
  0: "未订阅",
  1: "已订阅",
};

// 页面加载状态
const pageLoading = ref<boolean>(false);
// 获取用户数据
const getUserList = () => {
  if (pageLoading.value) return;
  pageLoading.value = false;
  PermissionsManageAPI.eventList()
    .then((data) => {
      pageLoading.value = false;
      tableData.value = data;
    })
    .catch(() => {
      pageLoading.value = false;
    });
};
// 防止多次点击
const btnLoading = ref<boolean>(false);
// 订阅操作
const subscribeEvent = (row: EventListInfo, type: number) => {
  if (btnLoading.value) return;
  btnLoading.value = false;
  PermissionsManageAPI.subscribeEvent({ eventType: row.eventType, subscribeStatus: type })
    .then((data) => {
      ElMessage.success("操纵成功");
      btnLoading.value = false;
      getUserList();
    })
    .catch(() => {
      btnLoading.value = false;
    });
};

onMounted(() => {
  getUserList();
});
</script>
